package com.shiguo365.market.display.fragment;

import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shiguo365.market.R;
import com.shiguo365.market.application.MyApplication;
import com.shiguo365.market.bean.Product;
import com.shiguo365.market.display.activity.ConfirmActivity;
import com.shiguo365.market.display.adapter.UserCartAdapter;
import com.shiguo365.market.display.util.RefreshUtils;
import com.shiguo365.market.display.view.ICartView;
import com.shiguo365.market.presenter.contract.ICartPresenter;
import com.shiguo365.market.presenter.implement.CartPresenter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by caomenglong on 16/7/7.
 */
public class CartFragment extends Fragment implements ICartView,SwipeRefreshLayout.OnRefreshListener {

    private static final String TAG = "CartFragment";

    @BindView(R.id.cart_recycler_view)
    protected RecyclerView recyclerView;

    @BindView(R.id.cart_refresh_layout)
    protected SwipeRefreshLayout refreshLayout;

    @BindView(R.id.cart_icon_no_data)
    protected TextView iconNoData;

    @BindView(R.id.textviewallprice)
    protected TextView mTvAllPrice;

    @BindView(R.id.buttonCreateOrder)
    protected Button createOrderButton;

    private List<JSONObject> mObjects = new ArrayList<JSONObject>();

    private UserCartAdapter mAdapter;

    private ICartPresenter mPresenter;

    private Integer uid = 1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_cart, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ButterKnife.bind(this,view);
        mPresenter = new CartPresenter(getActivity(),this);
        SharedPreferences preferences=this.getActivity().getSharedPreferences("data", Context.MODE_PRIVATE);
        uid=preferences.getInt("uid",1);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new UserCartAdapter(getActivity(),mPresenter, mObjects);
        recyclerView.setAdapter(mAdapter);

        RefreshUtils.initOnCreate(refreshLayout, this);
        RefreshUtils.refreshOnCreate(refreshLayout, this);

    }

    @Override
    public void onResume() {
        super.onResume();
        RefreshUtils.refreshOnCreate(refreshLayout, this);
    }


    //删除所有购物车
    @OnClick(R.id.buttonCartTrashAll)
    public void CartTrashAll(){
        AlertDialog.Builder dialog =new AlertDialog.Builder(this.getActivity());
        dialog.setTitle("清空购物车");
        dialog.setMessage("您确认要清空购物车吗？");
        dialog.setCancelable(false);
        dialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                mPresenter.deleteCart(MyApplication.getUID(),null);
            }
        });
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        dialog.show();
    }


    @OnClick(R.id.buttonCreateOrder)
    public void createOrder(){
        Log.e(TAG,"createOrder()");
        Intent intent=new Intent(this.getActivity(), ConfirmActivity.class);
        startActivity(intent);
    }

    @Override
    public void onRefresh() {
        mObjects.clear();
        Log.e(TAG,"onRefresh()"+String.valueOf(uid));
        mPresenter.getCartById(uid);
    }


    @Override
    public boolean onGetCartOk(@NonNull JSONObject result) {
        Log.e(TAG,result.toString());
        mObjects.clear();
        mTvAllPrice.setText("合计:￥"+result.getString("finalAmount"));

        Double finalAmount =Double.valueOf(result.getString("finalAmount"));

        if(finalAmount==0){

            createOrderButton.setClickable(false);
        }else{
            createOrderButton.setClickable(true);
        }

        JSONArray array1 = result.getJSONArray("prolist");
        for (int i = 0; i < array1.size(); i++) {
            JSONObject jo = (JSONObject) array1.get(i);
            mObjects.add(jo);
        }
        mAdapter.notifyDataSetChanged();
        iconNoData.setVisibility(array1.size() == 0 ? View.VISIBLE : View.GONE);
        return true;
    }

    @Override
    public void onGetCartFinished() {
        refreshLayout.setRefreshing(false);
    }

    @Override
    public void onGetCartFailed() {
        mTvAllPrice.setText("合计:￥0.00");
        iconNoData.setVisibility(View.VISIBLE);
    }

    @Override
    public void onDelCartOk() {
        mTvAllPrice.setText("合计:￥0.00");
        createOrderButton.setClickable(false);
        RefreshUtils.refreshOnCreate(refreshLayout, this);
    }
}
